<template>
	<view class="container">
		<u-navbar :is-back="false" :border-bottom="false" :title="address">
			<view class="slot-wrap">
				<view class="">
					<image mode="aspectFit" :src="weather_icon"></image>
				</view>
				<image @click.stop="toNear" mode="aspectFit" src="../../static/image/loc/myloc.png"></image>
			</view>
		</u-navbar>
		<!-- 地图 -->
		<map
		:style="{width: system.windowWidth+'px',height: system.windowHeight - system.statusBarHeight - 320 +'px'}" 
		:latitude="latitude"
		:longitude="longitude" 
		:markers="markers"
		@markertap="markerTap"
		@callouttap="calloutTap"
		@updated="updatedMap"
		></map>
		<view class="content" >
			<view class="search-wrap">
				<u-search
				:placeholder="placeholder" 
				@search="onSearch" 
				:animation="true" 
				v-model="keyword" 
				bg-color="#fff" 
				border-color="transparent" 
				:show-action="true" 
				height="80" 
				></u-search>	
			</view>
			<view class="hot">
				<view class="hot_item" v-for="(item,index) in hot_list" @click.stop="toSearch(item.keyword)" :key="index">
					<image :src="item.icon" mode="widthFix"></image>
					<text>{{item.name}}</text>
				</view>
			</view>
			<!-- 搜索的结果 -->
			<view class="address_result">
				<view class="address_box" v-for="(item,index) in markers_near" :key="index">
					<view class="address_icon">
						<image src="../../static/image/loc/near.png" mode="widthFix"></image>
					</view>
					<view class="address">
						<view class="item">
							{{item.name}}
						</view>
						<view class="item solid-bottom">
							{{item.address}}
						</view>
					</view>
					<u-button class="custom-style" @click="toDestinate(item)">前往</u-button>
					<!-- 调起高德APP导航 -->
					<!-- <u-button class="custom-style"><a :href="`androidamap://route/plan?sourceApplication=uni-travel&amp;dlat=${item.latitude}&amp;dlon=${item.longitude}&amp;dev=1&amp;dname=${item.name}&amp;t=0&amp`">到此处</a></u-button> -->
					
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import amap from "../../js_sdk/js-amap/amap-wx.js";
import { Debounce } from '../../utils/index.js'
import {mapActions,mapGetters} from 'vuex'
export default{
	data(){
		return{
			latitude:'',//纬度
			longitude:'',//经度
			markers:[],//标记点
			id:0, // 使用 marker点击事件 需要填写id
			mapKey:'20549ba8e49a4d6ab1898549debf308e',//高德地图的key
			title: 'map',
			mapInfo:{},//高德地图返回的信息
			amapPlugin:{},//引用高德地图插件
			system:{},//系统信息
			keyword:'',//搜索关键字
			keyword_list:[],//关键字列表
			address:'',//我的地址
		    desc:"",//位置描述
			weather_name:'',//天气
			weather_icon:'',//天气图标
			qing:'/static/image/weather/qing.png',//晴天
			yin:'/static/image/weather/yin.png',//阴天
			yu:'/static/image/weather/yu.png',//雨天
			xue:'/static/image/weather/xue.png',//雪
			hot_list:[
				{name:'吃',keyword:'',icon:require('../../static/image/loc/eat.png')},
				{name:'住',keyword:'旅店',icon:require('../../static/image/loc/ld.png')},
				{name:'游',keyword:'景点',icon:require('../../static/image/loc/jd.png')},
				{name:'玩',keyword:'娱乐',icon:require('../../static/image/loc/yl.png')},
				{name:'购',keyword:'商店',icon:require('../../static/image/loc/shop.png')},
			],
			scence_icon:require('../../static/image/loc/jq.png'),//景区图标
			near_icon:require('../../static/image/loc/near.png'),//附近图标
			myloc_icon:require('../../static/image/loc/myloc.png'),//我的位置图标
			placeholder:'输入搜索内容',
			timer:null,//关键字防抖
			select_address:{},//选中的地址
			markers_near:[],//搜索附近结果
		}
	},
	computed:{
		...mapGetters(['getLocation'])
	},
	onLoad() {
		this.getSystemInfo();
		
		// 从Vuex获取已保存的坐标
		const location = this.getLocation;
		if (location && location.latitude && location.longitude) {
			// 使用已保存的坐标（保定理工学院）
			this.latitude = location.latitude;
			this.longitude = location.longitude;
			console.log('使用已保存的坐标：', location);
		} else {
			// 如果没有保存的坐标，使用默认值（北京）
			this.latitude = 39.9042;
			this.longitude = 116.4074;
			console.log('使用默认坐标（北京）');
		}
		
		this.init();
	},
	onShow(){
		// 页面显示时更新坐标（从首页返回时可能坐标已更新）
		const location = this.getLocation;
		if (location && location.latitude && location.longitude) {
			this.latitude = location.latitude;
			this.longitude = location.longitude;
			console.log('location页面显示，更新坐标：', location);
			
			// 显示"我的位置"标记
			this.showMyLocation({
				latitude: this.latitude,
				longitude: this.longitude,
				id: 'myLocation'
			});
			
			// 强制更新视图
			this.$forceUpdate();
		}
	},
	methods:{
		...mapActions(['setLocation']),
		// 附近
		toNear(){
			uni.navigateTo({
				url:`./near?latitude=${this.latitude}&longitude=${this.longitude}`
			})
		},
		// 到目的地
		toDestinate(item){
			console.log("item",item);
			// 地址名，起始经纬度，结束经纬度
			let destName = item.name;
			let start = this.longitude+','+this.latitude;
			let dest = item.longitude+','+item.latitude;
			uni.navigateTo({
				url:`./nav?destName=${destName}&start=${start}&dest=${dest}`
			})
		},
		onSearch(keyword){
			this.getPoiAround(keyword);
		},
		toSearch(keyword){
			this.keyword = keyword;
			this.onSearch(keyword);
		},
		// 点击标记点位置触发
		markerTap(e){
			console.log("e",e);
			this.markers.forEach(item=>{
				if(item.id == e.detail.markerId){
					this.select_address = item;
				}
			})
		},
		// 点击标记点对应的气泡时触发
		calloutTap(e){
			console.log("e",e.detail.markerId);
			this.markers.forEach(item=>{
				if(item.id == e.detail.markerId){
					// 地址名，起始经纬度，结束经纬度
					let destName = item.name;
					let start = this.longitude+','+this.latitude;
					let dest = item.longitude+','+item.latitude;
					uni.navigateTo({
						url:`./nav?destName=${destName}&start=${start}&dest=${dest}`
					})
				}
			})
		},
		// 地图更新完成
		updatedMap(){
			console.log("loaded");
		},
		// 获取设备宽高
		getSystemInfo(){
			uni.getSystemInfo({
				success: (res) => {
					console.log("设备",res);
					this.system = res;
				},
				fail: (err) => {
					uni.showToast({
						title:JSON.stringify(res),
						icon:'none'
					});
				}
			})
		},
		chooseLocation(){
			uni.chooseLocation({
				success: (res)=> {
					console.log('位置名称：' + res.name);
					console.log('详细地址：' + res.address);
					console.log('纬度：' + res.latitude);
					console.log('经度：' + res.longitude);
					this.latitude = res.latitude;
					this.longitude = res.longitude;
					this.showMyLocation(res);
				}
			})
		},
		openLocation(){
			uni.openLocation({
				latitude: this.latitude,
				longitude: this.longitude,
				name:this.mapInfo.name,
				address:this.mapInfo.desc,
				success: (response)=> {
					console.log('response',response);
				}
			})
		},
		// 存储位置
		toSetLocation(res){
			this.address = res.name || res.address;//地址名字
			this.desc = res.desc;//地址描述
			this.setLocation({
				latitude:res.latitude,
				longitude:res.longitude
			});
		},
		// 显示我的位置
		showMyLocation(markers){
			this.markers.push({
				id:markers.id || '1',
				latitude:markers.latitude,
				longitude:markers.longitude,
				iconPath:this.myloc_icon,
				width:10,
				height:10,
				title:'我的位置'
			});
			this.$forceUpdate();
			this.toSetLocation(markers);
		},
		init(){
			this.amapPlugin = new amap.AMapWX({
				key:this.mapKey  //该key 是在高德中申请的微信小程序key
			});
			console.log("this.amapPlugin",this.amapPlugin);
			
			// 检查是否已有保存的坐标
			const location = this.getLocation;
			if (location && location.latitude && location.longitude) {
				// 已有坐标，直接显示标记和附近信息
				console.log('已有保存的坐标，不重新定位');
				this.showMyLocation({
					latitude: this.latitude,
					longitude: this.longitude,
					id: 'myLocation'
				});
				this.getPoiAround();
			} else {
				// 没有坐标，重新定位
				console.log('没有保存的坐标，执行定位');
				this.getRegeo();
			}
			
			this.getWeather();
		},
		//关键字变化 
		onChange(value){
			// console.log("value",value);
			// clearTimeout(this.timer);
			// this.timer = setTimeout(()=>{
			// 	this.getKeyword(value)
			// },500)
		},
		toKeyword(keyword){
			this.onSearch(keyword);
			this.keyword_list = [];
		},
		// 获取推荐关键字
		getKeyword(keywords){
			this.amapPlugin.getInputtips({
				keywords: keywords,
				location: '',
			    success: (data)=>{
				console.log("关键字",data);
				if(data && data.tips){
				  this.keyword_list = data.tips;
				}
			  }
			})
		},
		// 获取地址描述数据
		getRegeo(){
			this.amapPlugin.getRegeo({
				type: 'gcj02', //map 组件使用的经纬度是国测局坐标， type 为 gcj02
				success: (res)=> {
					console.log("高德地图",res);
					const latitude = res[0].latitude;
					const longitude = res[0].longitude;
					this.longitude = longitude;
					this.latitude = latitude;
					this.mapInfo = res[0];
					let markers = res[0];
					this.showMyLocation(markers);
					// this.openLocation();
					this.getPoiAround();
				},
				fail: (err) => {
					// this.chooseLocation();
					// this.getLocation();
					console.log("err",err);
					uni.showToast({
						title:JSON.stringify(err),
						icon:'none'
					});
				}
			});
		},
		// 获取周边服务
		getPoiAround(keyword){
			if(keyword){
				this.markers.splice(1,this.markers.length);
				this.$forceUpdate();
			}
			this.amapPlugin.getPoiAround({
			  querykeywords:keyword || '美食',
			  success: (data)=>{
				//成功回调
				console.log("data",data);
				let markers = data.markers;
				markers.map(item=>{
					// item.width = item.width;
					// item.height = item.height;
					item.width = 30;
					item.height = 30;
					item.id = item.latitude;
					item.iconPath = this.near_icon;
					item.alpha = 0.5;
					item.callout = {
						content:item.name+'\n\n'+item.address,
						fontSize:18,
						borderRadius:8,
						// bgColor:'#0xf5f5f5',
						padding:20,
						display:'BYCLICK',
						// display:'ALWAYS',
						textAlign:'center',
					};
					// item.label = {
					// 	content:item.name,
					// 	fontSize:18,
					// 	padding:20,
					// }
				})
				this.markers = [...this.markers,...markers];
				this.markers_near = this.markers.slice(1,this.markers.length)
				this.$forceUpdate();
			  },
			  fail: (info)=>{
				//失败回调
				console.log("info",info)
			  }
			})
		},
		// 查询指定城市的实时天气和预报天气
		getWeather(){
			this.amapPlugin.getWeather({
			  success: (data)=>{
				//成功回调
				console.log('天气',data);
				let weather = data.weather.data;
				this.weather_name = weather;
				if(weather.indexOf('晴')>-1){
					this.weather_icon = this.qing;
				}
				if(weather.indexOf('阴')>-1){
					this.weather_icon = this.yin;
				}
				if(weather.indexOf('多云')>-1){
					this.weather_icon = this.yin;
				}
				if(weather.indexOf('雨')>-1){
					this.weather_icon = this.yu;
				}
				if(weather.indexOf('雪')>-1){
					this.weather_icon = this.xue;
				}
			  },
			  fail: (info)=>{
				//失败回调
				uni.showToast({
					title:JSON.stringify(info),
					icon:'none'
				});
			  }
			})
		},
		
	}
}
</script>

<style lang="scss" scoped>
.search-wrap {
	// filter:drop-shadow(10rpx 10rpx 4rpx rgba(0,0,0,.05))
	box-shadow: 0 0 10px 2px rgba(0,0,0,.1);
	background-color: #fff;
	height: 80rpx;
	margin: 10rpx 20rpx;
	border-radius: 40rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	position: relative;
	.keyword_result{
		position: absolute;
		z-index: 100;
		top: 40px;
		height: 300rpx;
		overflow-y: auto;
		left:0;
		width: 60%;
		.keyword_item{
			height: 60rpx;
			line-height: 60rpx;
			border-bottom:1px solid #f5f5f5;
			background-color: #ffffff;
			text-indent: 20px;
		}
	}
}
.custom-style{
	background-color: #06CD5A;
	color:#fff;
	a{
		color:#fff;
		text-decoration: none;
	}
}
.address_box{
	display: flex;
	height: 120rpx;
	justify-content: space-between;
	box-sizing: border-box;
	padding: 0 10px;
	align-items: center;
	border-bottom:1px solid #f5f5f5;
	.address_icon{
		width: 40rpx;
		height: 40rpx;
		margin-right: 10px;
		image{
			width: 40rpx;
			height: 40rpx;
		}
	}
	.address{
		display: flex;
		flex:1;
		flex-direction: column;
		justify-content: space-between;
		height: 120rpx;
		.item{
			height: 60rpx;
			line-height: 60rpx;
			overflow: hidden;
			text-overflow:ellipsis;
			white-space: nowrap;
			width: 400rpx;
		}
	}
}

.content{
	width: 100%;
	flex:1;
	background-color: #fff;
	display: flex;
	flex-direction: column;
	overflow: auto;
	position: relative;
	.hot{
		width: 100%;
		display: flex;
		justify-content: space-around;
		align-items: center;
		height: 60px;
		.hot_item{
			display: flex;
			height: 40px;
			flex-direction: column;
			align-items: center;
			justify-content: space-between;
			image{
				width: 20px;
				height: 20px;
			}
			text{
				height: 20px;
			}
		}
		
	}
	.address_result{
		flex:1;
		overflow-y: auto;
		height: calc(100% - 50px);
	}
}
.slot-wrap{
	flex: 1;
	display: flex;
	justify-content: space-between;
	align-items: center;
	box-sizing: border-box;
	padding: 0 40rpx;
	image{
		width: 40rpx;
	}
}
.container{
	background-color: transparent;
	display: flex;
	flex-direction: column;
	height: 100vh;
	overflow: hidden;
}

</style>
